import React, { Component, createRef } from 'react'
import Taro, { eventCenter, getCurrentInstance, } from '@tarojs/taro';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import { connect } from 'react-redux';
import {
  Search, Skeleton,
} from '@antmjs/vantui';
import { CertifiedPrompt } from '@/components'

import PdsDropMenu from '@/components/common/pds_dropmenu';
import { findMapsByFieldName, findNameByFieldNameAndDictItemValue } from '@/services/api/common';
import { changeDecimalToPercentage, getPreviousMonthDate, parseDateFromStr } from '@/utils/fomatter';
import { queryFundPool } from '@/services/api/fund';
import PdsEmpty from '@/components/common/pds_empty';
import { stringifyUrl } from 'query-string';

import './index.scss'

class FundHome extends Component {

  state = {
    value: '产品',
    options: [],
    basicsList: [],
    refresherTriggered: false,
    skeletonLoading: true,
    userDetail: {},
    showPopup: false,
    setp: 0,

  }

  $instance = getCurrentInstance()

  componentWillMount() {
    this.requestFilterData()
    this.requestListData(false)

    const onShowEventId = this.$instance.router?.onShow ?? ''
    // 监听
    eventCenter.on(onShowEventId, this.onShow)
  }

  /**
   * 页面
   */
  onShow = () => {
    this.props.dispatch({
      type: 'certified/asyncGetUserDetail',
      callback: () => {
        let stepObj = this.props.certified?.stepObj
        // 判断三个校验条件是否都通过
        if (stepObj.step0 && stepObj.step1 && stepObj.step2) {
          this.setState({
            setp: 3
          })
        }
      }
    })
  }

  requestFilterData() {
    const { options } = this.state;
    // 策略类型
    const type_list = findMapsByFieldName('policy_type')
    var type_options_list: any[] = []
    for (let index = 0; index < type_list.length; index++) {
      const element = type_list[index];
      if (element['dictItemValue'] !== '-1') {
        type_options_list.push({ 'option_name': element['dictItemName'], 'option_value': element['dictItemValue'] })
      }
    }
    options.push({ 'name': '策略类型', "options": type_options_list });
    // 成立年限 自己造的
    var time_options_list: any[] = []
    var option_name = ['不满一年', '1-3年', '3-5年', '5年以上']
    //
    var currentDate = new Date();  // 当前日期
    var oneYear = getPreviousMonthDate(currentDate, 12);
    var threeYear = getPreviousMonthDate(currentDate, 12 * 3);
    var fiveYear = getPreviousMonthDate(currentDate, 12 * 5);
    var option_value = [`${currentDate.getTime()}-${oneYear}`, `${oneYear}-${threeYear}`, `${threeYear}-${fiveYear}`, `${fiveYear}-`]
    for (let index = 0; index < option_name.length; index++) {
      const name = option_name[index];
      const value = option_value[index];
      time_options_list.push({ 'option_name': name, 'option_value': value })
    }
    options.push({ 'name': '成立年限', "options": time_options_list });

    // 基金类型
    const category_list = findMapsByFieldName('fund_category')
    var category_options_list: any[] = []
    for (let index = 0; index < category_list.length; index++) {
      const element = category_list[index];
      if (element['dictItemValue'] !== '-1') {
        category_options_list.push({ 'option_name': element['dictItemName'], 'option_value': element['dictItemValue'] })
      }
    }
    options.push({ 'name': '基金类型', "options": category_options_list });

    // 基金规模
    const size_list = findMapsByFieldName('fund_size_type')
    var size_options_list: any[] = []
    for (let index = 0; index < size_list.length; index++) {
      const element = size_list[index];
      if (element['dictItemValue'] !== '-1') {
        size_options_list.push({ 'option_name': element['dictItemName'], 'option_value': element['dictItemValue'] })
      }
    }
    options.push({ 'name': '基金规模', "options": size_options_list });

    // 运作状态
    const status_list = findMapsByFieldName('operation_status')
    var status_options_list: any[] = []
    for (let index = 0; index < status_list.length; index++) {
      const element = status_list[index];
      if (element['dictItemValue'] !== '-1') {
        status_options_list.push({ 'option_name': element['dictItemName'], 'option_value': element['dictItemValue'] })
      }
    }
    options.push({ 'name': '运作状态', "options": status_options_list });
    // console.log(options)
  }

  requestListData(isAdd) {
    var fund_category = '', fund_mgr_type = '', operation_status = '', fund_size_type = '',
      policy_type = '', begin_date_ts = '', end_date_ts = '';

    const { options, basicsList } = this.state;
    // console.log(options)
    for (let index = 0; index < options.length; index++) {
      const element = options[index];
      if (element['select_option'] !== undefined && element['select_option']['option_value'] !== undefined) {
        if (element['name'] === '策略类型') {
          policy_type = element['select_option']['option_value'];
        } else if (element['name'] === '基金类型') {
          fund_category = element['select_option']['option_value'];
        } else if (element['name'] === '运作状态') {
          operation_status = element['select_option']['option_value'];
        } else if (element['name'] === '基金规模') {
          fund_size_type = element['select_option']['option_value'];
        } else if (element['name'] === '成立年限') {
          var time: string = element['select_option']['option_value'];
          var time_list = time.split('-')
          if (time_list.length == 2) {
            if (time_list[0].length > 0) {
              end_date_ts = time_list[0];
            }
            if (time_list[1].length > 0) {
              begin_date_ts = time_list[1];
            }
          }
        }
      }
    }

    var offset = isAdd ? basicsList.length : 0;
    queryFundPool({ fund_category, fund_mgr_type, operation_status, fund_size_type, policy_type, begin_date_ts, end_date_ts, offset }).then((resp) => {
      // console.log(resp.data)
      if (resp.code === 200) {
        if (isAdd) {
          var tempList: any[] = basicsList
          tempList.push(...resp.data)
          this.setState({ basicsList: tempList });
        } else {
          this.setState({ basicsList: resp.data });
        }

      }
      this.setState({ refresherTriggered: false, skeletonLoading: false })
    });

  }

  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }


  //自定义下拉刷新被触发
  onRefresherRefresh(e) {
    this.setState({ refresherTriggered: true })
    this.requestListData(false);
  }

  // 滚动到底部上拉加载
  scrolltoLower() {
    this.requestListData(true);
  }

  /**
   * 快速滑动不触发onScrollToLower 的bug
   * @param param0
   */
  onScroll = ({ detail: { scrollTop, scrollHeight } }) => {
    const { screenHeight, } = Taro.getSystemInfoSync()
    if (
      scrollTop + screenHeight + 100 >= scrollHeight
    ) {
      // this.scrolltoLower(); // 手动触发 onScrollToLower
    }
  };

  handleClose = () => {
    this.setState({
      showPopup: false
    })
    let stepObj = this.props.certified?.stepObj
    // 判断三个校验条件是否都通过
    if (stepObj.step0 && stepObj.step1 && stepObj.step2) {
      this.setState({
        setp: 3
      })
    }
  }
  /**
   * 点击一道投的产品
   */
  clickYdtFund(item) {
    const { setp } = this.state
    if (setp >= 3) {
      Taro.navigateTo({ url: stringifyUrl({ url: '/preIpoFund/fundDetail/index', query: { 'fundId': item['fundId'] } }, { encode: false }) })
    } else {
      this.setState({ showPopup: true })
    }


  }

  /**
   * 点击外部的产品
   *
   */
  clickXhFund(item) {
    const { setp } = this.state

    if (setp >= 3) {
      Taro.navigateTo({ url: stringifyUrl({ url: '/preIpoFund/manager/index', query: { 'fundManagerNo': item['fundManagerNo'] } }, { encode: false }) })
    } else {
      this.setState({ showPopup: true })

    }
  }

  /**
   * 点击搜索框
   */
  clickSearch() {

    const { setp } = this.state
    if (setp >= 3) {
      Taro.navigateTo({ url: '/preIpoFund/search/home/index' })
    } else {
      this.setState({ showPopup: true })
    }

  }

  render() {
    const { value, options, basicsList, refresherTriggered, showPopup, skeletonLoading, userDetail, setp } = this.state
    const scrollTop = 0
    const showDialog = this.props.certified?.showDialog ?? true
    return (
      <>
        <View className='page'>

          <Search placeholder='搜索私募基金产品' inputAlign='center' disabled={setp < 3} onClickInput={this.clickSearch.bind(this)} />
          <View className='select-type'>
            <PdsDropMenu title='成立年限' data={options.length == 0 ? [] : [options[1]]} onChange={(e) => {
              var tempData: any[] = Array.from(options)
              tempData[1] = e[0]
              this.setState({ options: tempData })
              this.requestListData(0)
            }}
            ></PdsDropMenu>

            <PdsDropMenu title='策略类型' data={options.length == 0 ? [] : [options[0]]} onChange={(e) => {
              var tempData: any[] = Array.from(options)
              tempData[0] = e[0]
              this.setState({ options: tempData })
              this.requestListData(0)
            }}
            ></PdsDropMenu>

            <PdsDropMenu title='基金类型' data={options.length == 0 ? [] : [options[2]]} onChange={(e) => {
              var tempData: any[] = Array.from(options)
              tempData[2] = e[0]
              this.setState({ options: tempData })
              this.requestListData(0)
            }}
            ></PdsDropMenu>

            <PdsDropMenu title='更多' data={[options[3], options[4]]} onChange={(e) => {
              console.log(e)
              var tempData: any[] = Array.from(options)
              tempData[3] = e[0]
              tempData[4] = e[1]
              this.setState({ options: tempData })
              this.requestListData(0)
            }}
            ></PdsDropMenu>
          </View>

          <Skeleton row={20} loading={skeletonLoading}>
            <ScrollView
              className='scrollview'
              scrollY
              scrollWithAnimation
              refresherEnabled
              scrollTop={scrollTop}
              refresherTriggered={refresherTriggered}
              lowerThreshold={150}
              onRefresherRefresh={this.onRefresherRefresh.bind(this)} // 使用箭头函数的时候 可以这样写 `onScrollToUpper={this.onScrollToUpper}`
              onScrollToLower={this.scrolltoLower.bind(this)}
              onScroll={this.onScroll.bind(this)}
            >
              {
                basicsList.length === 0 ? <PdsEmpty placeholderText='暂无相关数据'></PdsEmpty> : null
              }
              {

                basicsList.map((item, index) => {
                  return item['fundDataSource'] === 1 ?
                    <View className='fund-item ydt-fund-item' onClick={() => this.clickYdtFund(item)}>
                      <View className='title-icon'>
                        <Text>{item['fundName']}</Text>
                        <View className='ydt-icon'>
                          <Image src={require('@/assets/icons/public/fund_list_ydt.svg')} style={{ width: 10, height: 10, }}></Image>
                        </View>
                      </View>
                      <View className='fund-tag'>
                        {
                          (item['policyType'] !== undefined && item['policyType'] !== -1 && item['policyType'] !== 0) ? <View className='fund-tag-item ydt-tag-item'>{findNameByFieldNameAndDictItemValue('policy_type', item['policyType'])}</View> : null
                        }
                        {
                          (item['fundType'] !== undefined && item['fundType'] !== -1 && item['fundType'] !== 0) ? <View className='fund-tag-item ydt-tag-item '>{findNameByFieldNameAndDictItemValue('fund_type', item['fundType'])}</View> : null
                        }
                        {
                          (item['riskLevel'] !== undefined && item['riskLevel'] !== -1 && item['riskLevel'] !== 0) ? <View className='fund-tag-item ydt-tag-item'>{`产品评级:${findNameByFieldNameAndDictItemValue('risk_level', item['riskLevel'])}`}</View> : null
                        }
                      </View>
                      <View className='fund-context'>
                        <View className='fund-context-item  zdf'>

                          {
                            setp === 3 ?
                              <View className={Number(item['performance']['yearRate']) > 0 ? '.num-positive-text' : (Number(item['performance']['yearRate']) < 0 ? 'num-negative-text' : '')}><Text>{`${Number(item['performance']['yearRate']) > 0 ? '+' : ''}`}{changeDecimalToPercentage(item['performance']['yearRate'], 2)}</Text>%</View>
                              :
                              <View className='auth-see'>认证可见</View>

                          }
                          <View className='fund-context-item-desc'>近一年涨跌幅</View>
                        </View>
                        <View className='fund-context-item  fbq'>
                          <View className={setp === 3 ? "" : `fund-context-item-auth-see`}>{item['subscribeThreshold'].length > 0 ? `${Number(item['subscribeThreshold'] / 10000).toFixed(2)}万起` : '-'}</View>
                          <View className='fund-context-item-desc'>{item['fundClosingPeriod'].length > 0 ? item['fundClosingPeriod'] : '-'} | {findNameByFieldNameAndDictItemValue('risk_level', item['riskLevel'])}</View>
                        </View>
                        <View className='fund-context-item  dwjz'>
                          <View className={setp === 3 ? "" : `fund-context-item-auth-see`}>{Number(item['performance']['unitNet']).toFixed(4)}</View>
                          <View className='fund-context-item-desc'>{`单位净值(${(item['performance'] && item['performance']['netDate'] !== undefined && item['performance']['netDate'] !== null && item['performance']['netDate'] !== 0) ? parseDateFromStr(item['performance']['netDate'], 'MM-DD') : '-'})`}</View>
                        </View>
                      </View>
                    </View>

                    : <View className='fund-item xh-fund-item' onClick={() => this.clickXhFund(item)}>
                      <View className='title-icon'>
                        <Text>{item['fundName']}</Text>
                      </View>
                      <View className='fund-tag'>
                        {
                          (item['fundCode'] !== undefined) ? <View className='fund-tag-item xh-tag-item'>{item['fundCode']}</View> : null
                        }
                        {
                          (item['fundCategory'] !== undefined && item['fundCategory'] !== -1 && item['fundCategory'] !== 0) ? <View className='fund-tag-item xh-tag-item '>{findNameByFieldNameAndDictItemValue('fund_category', item['fundCategory'])}</View> : null
                        }
                      </View>
                      <View className='bottom'>
                        <View className='left-bottom'>
                          <Image src={require('@/assets/icons/public/fund_list_ydt.svg')} style={{ width: 10, height: 10, }}></Image>
                          <Text>暂未收录此基金</Text>
                        </View>
                        <View className={`right-bottom ${item['operationStatus'] === 1 ? 'right-bottom-active' : ''}`}>
                          {findNameByFieldNameAndDictItemValue('operation_status', item['operationStatus'])}
                        </View>
                      </View>
                    </View>

                })
              }
            </ScrollView >
          </Skeleton>
          {/* <FundAuthTipsPopup showPopUP={showAuthTipsPopup} step={setp}></FundAuthTipsPopup> */}
          {/* <FundPreIPOFilter showPopUP={showPopUP} data={['','','','']}   onSure={(e) =>{print(e)}} onClose={(e)=>{print(e)}}></FundPreIPOFilter> */}


        </View >
        <CertifiedPrompt dialogShow={showPopup} setDialogShow={() => this.setState({ showPopup: true })} setDialogClose={() => this.handleClose()}></CertifiedPrompt>

      </>

    );
  }
}
const mapStateToProps = (state) => {
  return {
    certified: state.certified, //这里的example表示后面用this.props.example获取state（根节点）中exmpale命名空间（model的example.js中的state所有数据）的数据
  }
}

export default connect(mapStateToProps)(FundHome);
